#!/usr/bin/env python
"""
The MIT License (MIT)
Copyright © 2022 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-esp32-walkie-talkie
"""
import socket
import time

HOST = ('localhost', 7890)
CHUNK = 1024 * 1

# WAVE_FILE = '../../pcm/tone1_bits16_rate16000_mono.wavv'
WAVE_FILE = '../../pcm/pingfanzhilu.wav'


def main():
	udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	wave_sample_mv = memoryview(bytearray(CHUNK))

	with open(WAVE_FILE, 'rb') as wave_samples:
		wave_samples.seek(44)

		print('sending wave samples...')
		while True:
			length = wave_samples.readinto(wave_sample_mv)

			if length:
				udp_client.sendto(wave_sample_mv[0:length], (HOST))

				# 延时必须在 0.02~0.03 之间
				# 延时 0.01 为快放，延时 0.04 为慢放，原因未知
				time.sleep(0.02)
			else:
				wave_samples.seek(44)
				time.sleep(1)


if __name__ == '__main__':
	try:
		main()
	except KeyboardInterrupt:
		exit(0)
